{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The Qmod Workshop - Part 2: Higher-Level Concepts\n",
    "\n",
    "This is the second part of the Qmod workshop, covering exercises 6 through 10. Make sure to go through Part 1 before continuing with this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from classiq import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise 6 - Exponentiation and Pauli Operators\n",
    "\n",
    "The Qmod language supports different classical types: scalars, arrays, and structs. Structs are objects with member variables, or fields.\n",
    "\n",
    "See also [Classical Types](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/classical-types/#structs).\n",
    "\n",
    "The builtin struct type `PauliTerm` is defined as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 138,
   "metadata": {},
   "outputs": [],
   "source": [
    "@struct\n",
    "class PauliTerm:\n",
    "    pauli: CArray[Pauli]\n",
    "    coefficient: CReal"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that `Pauli` is an enum for all the Pauli matrices (I, X, Y, Z).\n",
    "\n",
    "Pauli based hamiltonian can be represented as a list of `PauliTerm`s. A Pauli operator defined this way is the argument to a hamiltonian evolution functions.\n",
    "\n",
    "In this exercise we will use the Suzuki-Trotter function to find the evolution of `H=0.5XZXX + 0.25YIZI + 0.3 XIZY` (captured as a literal value for the pauli-operator), with the evolution coefficient being 3, the order being 2, and use 4 repetitions.\n",
    "\n",
    "The declaration of the `suzuki_trotter` function is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "metadata": {},
   "outputs": [],
   "source": [
    "@qfunc(external=True)\n",
    "def suzuki_trotter(\n",
    "    pauli_operator: CArray[PauliTerm],\n",
    "    evolution_coefficient: CReal,\n",
    "    order: CInt,\n",
    "    repetitions: CInt,\n",
    "    qbv: QArray[QBit],\n",
    ") -> None:\n",
    "    pass\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fill in the missing parts of the following code in order to complete this exercise:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 142,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/de4a5f91-3abf-4e71-8a52-81128cd3db9c?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def main(q: Output[QArray[QBit]]) -> None:\n",
    "    allocate(4, q)\n",
    "    suzuki_trotter(\n",
    "        [ PauliTerm(pauli=[Pauli.X, Pauli.Z, Pauli.X, Pauli.X], coefficient=0.5),\n",
    "          PauliTerm(pauli=[Pauli.Y, Pauli.I, Pauli.Z, Pauli.I], coefficient=0.25),\n",
    "          PauliTerm(pauli=[Pauli.X, Pauli.I, Pauli.Z, Pauli.Y], coefficient=0.3)\n",
    "        ],\n",
    "        evolution_coefficient=3,\n",
    "        repetitions=4,\n",
    "        order=2,\n",
    "        qbv=q,\n",
    "    )\n",
    "\n",
    "\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise 7 - Basic Arithmetics\n",
    "\n",
    "#### Exercise 7a\n",
    "In this exercise we will use quantum numeric variables and calculate expressions over them.\n",
    "\n",
    "See details on the syntax of numeric types under [Quantum types](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/quantum-types/#syntax).\n",
    "See more on quantum expressions under [Numeric assignment](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/numeric-assignment/)\n",
    "\n",
    "Create the following quantum programs:\n",
    "1. Initialize variables `x=2`, `y=7` and computes `res = x + y`.\n",
    "2. Initialize variables `x=2`, `y=7` and computes `res = x * y`.\n",
    "3. Initialize variables `x=2`, `y=7`, `z=1` and computes `res = x * y - z`.\n",
    "\n",
    "Guidance:\n",
    "* Use the operator `|=` to perform out-of-place assignment of arithmetic expression.\n",
    "* To initialize the variables, use the function `prepare_int`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/9c51893c-6451-41e4-a1b9-224f63b798e1?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "@qfunc\n",
    "def main(res: Output[QNum]):\n",
    "    x = QNum('x')\n",
    "    y = QNum('y')\n",
    "\n",
    "    prepare_int(2,x)\n",
    "    prepare_int(7,y)\n",
    "\n",
    "    res |= x + y\n",
    "\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/32a9636b-cfa4-4eb0-80da-8658ab9cd574?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "@qfunc\n",
    "def main(res: Output[QNum]):\n",
    "    x = QNum('x')\n",
    "    y = QNum('y')\n",
    "\n",
    "    prepare_int(2,x)\n",
    "    prepare_int(7,y)\n",
    "\n",
    "    res |= x * y\n",
    "\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/14b1cbc2-c90a-4d89-a151-3be386fcdfb5?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "@qfunc\n",
    "def main(res: Output[QNum]):\n",
    "    x = QNum('x')\n",
    "    y = QNum('y')\n",
    "    z = QNum('z')\n",
    "\n",
    "    prepare_int(2,x)\n",
    "    prepare_int(7,y)\n",
    "    prepare_int(1,z)\n",
    "\n",
    "    res |= x + y - z\n",
    "\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Exercise 7b\n",
    "Declare `x` to be a 2-qubit variable and `y` to be 3-qubit variable.\n",
    "\n",
    "We will perform an addition of two superposition states: `x` is an equal superposition of `0` and `2`, and `y` is an equal superposition of `1`, `2`, `3`, and `6`.\n",
    "\n",
    "1. Use `prepare_state` to initialize `x` and `y`. Note that `prepare_state` works with probabilities, not amplitudes.\n",
    "   The declaration of the `prepare_state` function is:\n",
    "   ```\n",
    "        @qfunc(external=True)\n",
    "        def prepare_state(\n",
    "            probabilities: CArray[CReal],\n",
    "            bound: CReal,\n",
    "            out: Output[QArray[QBit]],\n",
    "        ) -> None:\n",
    "            pass\n",
    "   ```\n",
    "   (Set the bound to 0 in your code)\n",
    "2. Compute `res = x + y`. Execute the resulting circuit. What did you get?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'meas': 0.0}: 1027, {'meas': 1.0}: 1021]"
      ]
     },
     "execution_count": 146,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "@qfunc\n",
    "def main():\n",
    "    x = QBit('x')\n",
    "    prepare_state(probabilities=[1/2,1/2],bound= 0, out=x)\n",
    "    #y = QBit('y')\n",
    "    #prepare_state(probabilities=[1/2,1/2],bound= 0, out=y)\n",
    "    \n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "job = execute(qprog)\n",
    "results = job.result()\n",
    "parsed_counts = results[0].value.parsed_counts\n",
    "parsed_counts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "metadata": {},
   "outputs": [],
   "source": [
    "## The x_variable measures state 0 more (corresponding to number 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'meas': 0.0}: 558,\n",
       " {'meas': 1.0}: 527,\n",
       " {'meas': 3.0}: 499,\n",
       " {'meas': 2.0}: 464]"
      ]
     },
     "execution_count": 148,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@qfunc\n",
    "def main():\n",
    "    y = QArray('y')\n",
    "    prepare_state(probabilities=[1/4,1/4,1/4,1/4],bound= 0, out=y)\n",
    "    \n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "job = execute(qprog)\n",
    "results = job.result()\n",
    "parsed_counts = results[0].value.parsed_counts\n",
    "parsed_counts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "metadata": {},
   "outputs": [],
   "source": [
    "## The y_variable measures state 0 more (corresponding to number 6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/4163a826-2945-4422-b84f-92bc85a2b5d2?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "@qfunc\n",
    "def main(res: Output[QNum]):\n",
    "    x = QNum('x')\n",
    "    y = QNum('y')\n",
    "\n",
    "    prepare_int(1,x) #(subtract the 1 later)\n",
    "    prepare_int(6,y)\n",
    "\n",
    "    res |= x -1 + y \n",
    "\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Exercise 8 - Within-Apply\n",
    "\n",
    "The within-apply statement applies the pattern `U_dagger V U` that appears frequently in quantum computing.\n",
    "It allows you to compute some function `V` within the context of another function `U`, and afterward uncompute `U` in order to release auxiliary qubits storing intermediate results.\n",
    "\n",
    "See also [Within Apply](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/within-apply/).\n",
    "\n",
    "#### Exercise 8a\n",
    "\n",
    "In this exercise, we will use within-apply to compute an arithmetic expression in steps.\n",
    "\n",
    "Use the `within_apply` operation to calculate `res = x + y + z` from a two-variable addition building block with the following steps:\n",
    "1. Add `x` and `y`\n",
    "2. Add the result to `z`\n",
    "3. Uncompute the result of the first operation\n",
    "\n",
    "For simplicity, initialize the registers to simple integers: `x=3`, `y=5`, `z=2`.\n",
    "\n",
    "Hints:\n",
    "\n",
    "* Use a temporary variable.\n",
    "* Wrap the arithmetic operation in a function.\n",
    "\n",
    "Execute the circuit and make sure you obtain the expected result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 348,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/1400508e-7789-4852-817b-faa408bc022f?version=0.41.2\n",
      "Synthesized circuit width: 16 depth: 100\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "@qfunc\n",
    "def linear_func(x:QNum, y:QNum, res: Output[QNum]):\n",
    "    res |= x + y\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def main(res: Output[QNum]):\n",
    "    x = QNum('x')\n",
    "    y = QNum('y')\n",
    "    z = QNum('z')\n",
    "    prepare_int(3, x)\n",
    "    prepare_int(5, y)\n",
    "    prepare_int(2, z)\n",
    "\n",
    "    tmp = QNum('tmp')\n",
    "    within_apply(compute= lambda: linear_func(x, y, tmp),\n",
    "                action= lambda: linear_func(tmp, z, res))\n",
    "\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)\n",
    "\n",
    "def print_depth_width(quantum_program):\n",
    "    generated_circuit = QuantumProgram.parse_raw(quantum_program)\n",
    "    print(\"Synthesized circuit width:\", generated_circuit.data.width, \"depth:\", generated_circuit.transpiled_circuit.depth)\n",
    "print_depth_width(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Exercise 8b\n",
    "\n",
    "Why should we use `within-apply` and not just write three concatenated functions?\n",
    "To understand the motivation, we will create another arithmetic circuit.\n",
    "This time, however, we will also set Classiq’s synthesis engine to optimize on the circuit’s number of qubits, i.e., its width.\n",
    "\n",
    "Setting constraints can be done via the `set_constraints` operation - see [here](https://docs.classiq.io/latest/user-guide/platform/synthesis/constraints/).\n",
    "\n",
    "Perform the operation `res = w + x + y + z`, where w is initialized to 4 and the rest as before:\n",
    "\n",
    "1. Add `x` and `y` (as part of the `within_apply` operation)\n",
    "2. Add the result to `z` (as part of the within_apply operation)\n",
    "3. Uncompute the result of the first operation (as part of the `within_apply` operation)\n",
    "4. Add the result of the second operation to `w`. There’s no need to perform another uncomputation, as this brings our calculation to an end.\n",
    "\n",
    "Create the model, optimize on the circuit’s width, and run the circuit. Can you identify where qubits have been released and reused?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 286,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/0f9a35d1-2b36-41ba-8d90-56feb9809735?version=0.41.2\n",
      "Opening: https://platform.classiq.io/circuit/d62abc28-a6a1-4a6f-a9a4-ae9317340228?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "@qfunc\n",
    "def main(res: Output[QNum]):\n",
    "    x = QNum('x')\n",
    "    y = QNum('y')\n",
    "    z = QNum('z')\n",
    "    w = QNum('w')\n",
    "\n",
    "    prepare_int(3,x)\n",
    "    prepare_int(5,y)\n",
    "    prepare_int(2,z)\n",
    "    prepare_int(4,w)\n",
    "\n",
    "    a = x + y \n",
    "    b = a + z\n",
    "    res |= b + w\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)\n",
    "\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Bonus: Use a Single Arithmetic Expression\n",
    "\n",
    "What happens when we don't manually decompose this expression?\n",
    "\n",
    "Use Classiq’s arithmetic engine to calculate `res |= x + y + z + w` and optimize for width.\n",
    "Look at the resulting quantum program - can you identify the computation and uncomputation blocks? What else did you notice?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 296,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/4e054d02-afe2-4e4a-b59b-ddcc18e1ec7c?version=0.41.2\n",
      "Opening: https://platform.classiq.io/circuit/2b2d18b9-134f-45c7-829d-8a11399d3248?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "from classiq import *\n",
    "\n",
    "# Your code here:\n",
    "@qfunc\n",
    "def main(res: Output[QNum]):\n",
    "    x = QNum('x')\n",
    "    y = QNum('y')\n",
    "    z = QNum('z')\n",
    "    w = QNum('w')\n",
    "\n",
    "    prepare_int(3,x)\n",
    "    prepare_int(5,y)\n",
    "    prepare_int(2,z)\n",
    "    prepare_int(4,w)\n",
    "\n",
    "    res |= x + y + z + w\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise 9 - In-place Arithmetics\n",
    "\n",
    "For the following exercise we will use numeric quantum variables that represent fixed-point reals.\n",
    "\n",
    "Arithmetic expressions can be calculated in-place into a target variable, without allocating new qubits to store the result. This is done using the in-place-xor operator.\n",
    "\n",
    "See also [Numeric assignment](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/numeric-assignment/#semantics).\n",
    "\n",
    "In-place assignment is often used to nest arithmetic expressions under quantum operators. Note that out-of-place assignment requires its left-value variable to be un-initialized, and therefore cannot be used under an operator if the variable is declared outside its scope. Applying operators to arithmetic expressions is required in many algorithms. One example is the piecewise evaluation of mathematical functions - calculating different expressions over `x` depending on the subdomain where `x` falls.\n",
    "\n",
    "For this exercise, replace the missing parts in the code snippet below to evaluate the result of:\n",
    "\n",
    "$$\n",
    "f(x) = \\begin{cases}\n",
    "      2x + 1 & \\text{ if } 0 \\leq x < 0.5 \\\\\n",
    "      x + 0.5 & \\text{ if } 0.5 \\leq x < 1\n",
    "   \\end{cases}\n",
    "$$\n",
    "\n",
    "Notes:\n",
    "- We cannot use `x` directly as the control variable in a `constrol` operator, because it also occurs in the nested scope. to determine if `x` is in the lower or higher half of the domain we duplicate the most significant bit onto a separate variable called `label`.\n",
    "- In Python assignment operators cannot be used in lambda expressions, so the computation of the function needs to be factored out to a named Python function (but not necessarily a Qmod function).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 297,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/d1c97569-898d-4e52-8269-6a586d1fce40?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "\n",
    "from classiq import *\n",
    "\n",
    "\n",
    "def linear_func(a: float, b: float, x: QNum, res: QNum) -> None:\n",
    "    res ^= a * x + b\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def dup_msb(qba: QArray[QBit], msb: QBit) -> None:\n",
    "    CX(qba[qba.len - 1], msb)\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def main(x: Output[QNum[3, False, 3]], res: Output[QNum[5, False, 3]]) -> None:\n",
    "    allocate(5, res)\n",
    "    allocate(3, x)\n",
    "    hadamard_transform(x)\n",
    "\n",
    "    label = QArray(\"label\")\n",
    "    allocate(1, label)\n",
    "\n",
    "    dup_msb(x, label)\n",
    "    control(label, lambda: linear_func(1.0, 0.5, x, res))  # 0.5 <= x < 1.0\n",
    "    X(label)\n",
    "    control(label, lambda: linear_func(2.0, 1.0, x, res))  # 0.0 <= x < 0.5\n",
    "\n",
    "\n",
    "qmod = create_model(main)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise 10 - State-preparation Algorithm using Quantum-if\n",
    "\n",
    "#### Binding\n",
    "The `bind` operation allows to convert smoothly between different quantum types and split or slice bits when necessary. Here’s an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 298,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/d0c9e9b9-f518-44ec-bed9-7f46b091ae2e?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "\n",
    "\n",
    "\n",
    "from classiq import *\n",
    "from math import pi\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def main(res: Output[QArray[QBit]]) -> None:\n",
    "    x: QArray[QBit] = QArray(\"x\")\n",
    "    allocate(3, x)\n",
    "    hadamard_transform(x)\n",
    "\n",
    "    lsb = QBit(\"lsb\")\n",
    "    msb = QNum(\"msb\", 2, False, 0)\n",
    "    bind(x, [lsb, msb])\n",
    "\n",
    "    control(msb == 1, lambda: RY(pi / 3, lsb))   # msb==1 <==> bit1 bit2 == 01 (binary of decimal 1)\n",
    "\n",
    "    bind([lsb, msb], res)\n",
    "\n",
    "model = create_model(main)\n",
    "qprog = synthesize(model)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first `bind` operation splits the 3-qubit register `x` into the 2-qubit and single-qubit registers `lsb` and `msb`, respectively.\n",
    "\n",
    "After the `bind` operation:\n",
    "1. The registers `lsb` and `msb` can be operated on as separated registers.\n",
    "2. The register`x` is consumed and can no longer be used.\n",
    "\n",
    "The second `bind` operation concatenates the registers to the output register `res`.\n",
    "\n",
    "For this exercise, fill in the missing code parts in the above snippet and use the `control` statement to manually generate the following lovely 3-qubit probability distribution: `[1/8, 1/8, 1/8, -sqrt(3)/16, 1/8 + sqrt(3)/16, 1/8, 1/8, 1/8, 1/8]`.\n",
    "\n",
    "The following series of gates generate it:\n",
    "\n",
    "Perform the Hadamard transform on all three qubits.\n",
    "\n",
    "Apply a rotation on the LSB (least-significant bit) conditioned by the MSB being |0> and the second to last MSB being |1>. How would you write this condition using a QNum?\n",
    "\n",
    "The following series of gates generate it:\n",
    "1. Perform the Hadamard transform on all three qubits.\n",
    "2. Apply a `pi/3` rotation on the LSB (least-significant bit) conditioned by the MSB being |0> and the second to last MSB being |1>. How would you write this condition using a QNum?\n",
    "\n",
    "If you want to validate your results without looking at the full solution, compare them to running using Classiq’s built-in `prepare_state` function.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 346,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/fe65e99e-1ed0-4216-8141-9b6c88fd51e1?version=0.41.2\n"
     ]
    }
   ],
   "source": [
    "from classiq import *\n",
    "from classiq.qmod.symbolic import sqrt\n",
    "\n",
    "prob_list= [\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "            -sqrt(3) / 16,\n",
    "            1 / 8 + sqrt(3) / 16,\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "        ]\n",
    "\n",
    "@qfunc\n",
    "def pre_prepared_state(q: QArray[QBit]) -> None:\n",
    "    prepare_state(\n",
    "        [\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "            -sqrt(3) / 16,\n",
    "            1 / 8 + sqrt(3) / 16,\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "            1 / 8,\n",
    "        ],\n",
    "        0.0,\n",
    "        q,\n",
    "    )\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def main(res: Output[QArray[QBit]]):\n",
    "    x = QArray(\"x\")\n",
    "    allocate(3, x)\n",
    "    #pre_prepared_state(x)\n",
    "    hadamard_transform(x)\n",
    "    \n",
    "    lsb = QBit(\"lsb\")\n",
    "    msb = QNum(\"msb\", 2, False, 0)\n",
    "    bind(x, [lsb, msb])\n",
    "    \n",
    "    control(msb == 0, lambda: RY(pi / 3, lsb)) \n",
    "    control(msb == 1, lambda: RY(pi / 3, lsb)) \n",
    "    bind([lsb, msb], res)\n",
    "    \n",
    "\n",
    "model = create_model(main)\n",
    "qprog = synthesize(model)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
